﻿using System;
using log4net.Appender;
using System.Web;
using log4net.Core;

namespace Blazing.WebFacade.Logging
{
    public class CountQueriesAppender : AppenderSkeleton
    {
        private static readonly object Key = new object();

        /// <summary>
        /// Gets the number of database queries that have been executed
        /// during this web request so far.
        /// </summary>
        /// <value>The current query count.</value>
        public static int CurrentQueryCount
        {
            get
            {
                var val = HttpContext.Current.Items[Key];
                return val == null ? 0 : (int)val;
            }
        }

        protected override void Append(LoggingEvent loggingEvent)
        {
            var items = HttpContext.Current.Items;
            if (items.Contains(Key))
            {
                // increase query count
                items[Key] = 1 + (int)items[Key];
            }
            else
            {
                // first query, initialize with 1
                items[Key] = 1;
            }
        }
    }
}
